package com.fhnew.app.ui.dialogactivity;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageInfo;

import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.Resbuildground;
import com.fhnew.app.model.network.entity.req.Resmsg;
import com.fhnew.app.model.network.entity.req.Respass;
import com.fhnew.app.util.Md5;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SetingActivity extends Activity {

    private ImageView close;
    private TextView voicesseting;
    private TextView changepass;
    private TextView appversion;
    private ImageView userimgseting;
    private TextView usernamestext;
    private TextView dengjitext;
    private TextView voicesset;
    private TextView loginout;
    private TextView code_img;
    private TextView changebt;
    private TextView version;
    private TextView version1;
    private SeekBar yinyueseek;
    private SeekBar yinxiaoseek;
    private EditText changephone;
    private EditText changepasset;
    private EditText newchangepass;
    private EditText rigistusername;
    private RelativeLayout voicelayout;
    private LinearLayout passlayout;
    private LinearLayout applayout;
    private int yinyue;
    private int yinxiao;
    private AudioManager audioManager = null;

    private UserModel userModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seting);

        userModel = UserModel.getInstance(this);

        Constants.backgroundvoic = false;
        close = findViewById(R.id.close);
        voicesseting = findViewById(R.id.voicesseting);
        changepass = findViewById(R.id.changepass);
        appversion = findViewById(R.id.appversion);
        userimgseting = findViewById(R.id.userimgseting);
        usernamestext = findViewById(R.id.usernamestext);
        dengjitext = findViewById(R.id.dengjitext);
        voicesset = findViewById(R.id.voicesset);
        code_img = findViewById(R.id.code_img);
        changephone = findViewById(R.id.changephone);
        yinyueseek = findViewById(R.id.yinyueseek);
        yinxiaoseek = findViewById(R.id.yinxiaoseek);
        loginout = findViewById(R.id.loginout);
        voicelayout = findViewById(R.id.voicelayout);
        passlayout = findViewById(R.id.passlayout);
        changebt = findViewById(R.id.changebt);
        changepasset = findViewById(R.id.changepasset);
        newchangepass = findViewById(R.id.newchangepass);
        rigistusername = findViewById(R.id.rigistusername);
        applayout = findViewById(R.id.applayout);
        version = findViewById(R.id.version);
        version1 = findViewById(R.id.version1);
        try {
            PackageManager manager = SetingActivity.this.getPackageManager();
            PackageInfo packageInfo = manager.getPackageInfo(SetingActivity.this.getPackageName(), 0);
            version.setText("最新版本"+Constants.versionName+"\n当前版本" + Constants.versionName);
            version1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(Constants.versionName) && !Constants.versionName.equals(packageInfo.versionName)) {
                        Uri uri = Uri.parse(Constants.versionurl + "");
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    } else {
                        Toast.makeText(SetingActivity.this, "当前已经是最新版本", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        } catch (Exception e) {
        }

        if (!TextUtils.isEmpty(UserModel.Token)) {
            userimgseting.setImageResource(R.mipmap.ic_launcher);
            usernamestext.setText(UserModel.user.userName);
            dengjitext.setText("暂未评级");
            loginout.setVisibility(View.VISIBLE);
        } else {
            userimgseting.setImageResource(R.mipmap.ic_launcher);
            usernamestext.setText("未登录");
            dengjitext.setText("未登录");
            loginout.setVisibility(View.GONE);
        }


        voicesseting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                voicelayout.setVisibility(View.VISIBLE);
                passlayout.setVisibility(View.GONE);
                applayout.setVisibility(View.GONE);
                btcolor();
                voicesseting.setBackgroundResource(R.mipmap.settingup);
            }
        });
        changepass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                applayout.setVisibility(View.GONE);
                voicelayout.setVisibility(View.GONE);
                passlayout.setVisibility(View.VISIBLE);
                btcolor();
                changepass.setBackgroundResource(R.mipmap.settingup);
            }
        });
        appversion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                voicelayout.setVisibility(View.GONE);
                passlayout.setVisibility(View.GONE);
                applayout.setVisibility(View.VISIBLE);
                btcolor();
                appversion.setBackgroundResource(R.mipmap.settingup);
            }
        });


        changebt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(changephone.getText().toString().trim())) {
                    Toast.makeText(SetingActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(changepasset.getText().toString().trim())) {
                    Toast.makeText(SetingActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(newchangepass.getText().toString().trim())) {
                    Toast.makeText(SetingActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(rigistusername.getText().toString().trim())) {
                    Toast.makeText(SetingActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                changepassword(changephone.getText().toString().trim(), rigistusername.getText().toString().trim(),
                        Md5.toMd5(changepasset.getText().toString().trim()), Md5.toMd5(newchangepass.getText().toString().trim()));
            }
        });


        code_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(changephone.getText().toString().trim())) {
                    sendmsg(changephone.getText().toString().trim());
                    timer.start();
                } else {
                    Toast.makeText(SetingActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }
            }
        });
        loginout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserModel.Token = null;
                UserModel.user = null;
                //断开Socket
//                WebSocketUtils2.getInstance().ondestoryWebsocket();
                userModel.loginOut();
                // 这里开始网络请求
                HttpJsonUtils.getHttpApiInstance()
                        .logout(Constants.getuseAdress() + "api/m/logout", UserModel.Token)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new CustomObserver<Resbuildground>() {
                            @Override
                            protected void onCustomNext(Resbuildground resLogin) {
                                finish();
                            }

                            @Override
                            protected void onSubscribeCustom(Disposable disposable) {
                            }

                            @Override
                            protected void onErrorCustom(Throwable e) {

                            }
                        });
            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        /**
         * 音乐控制
         */
        audioManager = (AudioManager)

                getSystemService(Service.AUDIO_SERVICE);
        yinyueseek.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
        yinxiaoseek.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM));
        //音乐设置
        yinyueseek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()

        {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                yinyue = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int result = 0;
                if (yinyue > audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)) {
//                    加音量
                    result = yinyue - audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

                    for (int i = 0; i < result; i++) {
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,
                                AudioManager.FLAG_PLAY_SOUND);
                    }
                } else {
//                    减音量
                    result = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) - yinyue;
                    for (int i = 0; i < result; i++) {
                        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER,
                                AudioManager.FLAG_PLAY_SOUND);
                    }

                }


            }
        });


        //音效设置
        yinxiaoseek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()

        {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                yinxiao = progress;
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int result = 0;
                if (yinxiao > audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM)) {
//                    加音量
                    result = yinxiao - audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);

                    for (int i = 0; i < result; i++) {
                        audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_RAISE,
                                AudioManager.FLAG_PLAY_SOUND);
                    }
                } else {
//                    减音量
                    result = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM) - yinxiao;
                    for (int i = 0; i < result; i++) {
                        audioManager.adjustStreamVolume(AudioManager.STREAM_SYSTEM, AudioManager.ADJUST_LOWER,
                                AudioManager.FLAG_PLAY_SOUND);
                    }

                }


            }
        });

    }

    private void btcolor() {
        voicesseting.setBackgroundResource(R.mipmap.settingbt);
        changepass.setBackgroundResource(R.mipmap.settingbt);
        appversion.setBackgroundResource(R.mipmap.settingbt);
    }

    private void changepassword(String trim, String trim1, String s, String s1) {
        HttpJsonUtils.getHttpApiInstance()
                .changepass(Constants.getuseAdress() + "api/m/forgotPassword", trim, trim1, s, s1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Respass>() {
                    @Override
                    protected void onCustomNext(Respass resLogin) {
                        if (resLogin.status) {
                            timer.cancel();
                            Toast.makeText(SetingActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(SetingActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        Toast.makeText(SetingActivity.this, "输入无效", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onPause() {
        super.onPause();
//        EventBus.getDefault().post(new ReloginEvent("100"));
    }

    /**
     * 发送验证码
     *
     * @param trim
     */
    private void sendmsg(String trim) {
        HttpJsonUtils.getHttpApiInstance()
                .sendmsg(Constants.getuseAdress() + "api/m/smsCode/" + trim, "1", "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resmsg>() {
                    @Override
                    protected void onCustomNext(Resmsg resLogin) {
                        if (resLogin.status) {
                            //成功
                            Toast.makeText(SetingActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(SetingActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        timer.cancel();
                    }
                });
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            code_img.setText((millisUntilFinished / 1000) + "S后重发");
            code_img.setEnabled(false);
        }

        @Override
        public void onFinish() {
            code_img.setEnabled(true);
            code_img.setText("获取验证码");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
